package com.mjh.zhujianju.service.agency.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.SysUserService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.enums.EStatus;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.livew.framework.utils.XTStringUtils;
import com.mjh.zhujianju.dao.agency.DepartmentMapper;
import com.mjh.zhujianju.enums.BusinessEnum;
import com.mjh.zhujianju.model.agency.DepartmentEO;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.service.agency.DepartmentService;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.service.base.ContentService;
import com.mjh.zhujianju.util.FileUrlAdapter;
import com.mjh.zhujianju.vo.agency.DepartmentVO;
import com.mjh.zhujianju.vo.base.SysUserVO;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<DepartmentEO> implements DepartmentService {

	@Resource
	private DepartmentMapper departmentMapper;

	@Resource
	private FileService fileService;

	@Resource
	private DeptUserService deptUserService;

	@Resource
	private ContentService contentService;

	@Autowired
	private SysUserService sysUserService;

	public DepartmentServiceImpl(DepartmentMapper departmentMapper) {
		super(departmentMapper);
	}

	@Override
	public PagedResult<DepartmentVO> getVOList(DepartmentEO vo) {
		Integer pageNo = vo.getPageNo() == null ? 1 : vo.getPageNo();
		Integer pageSize = vo.getPageSize() == null ? 15 : vo.getPageSize();
		PageHelper.startPage(pageNo, pageSize);
		List<DepartmentEO> list = departmentMapper.selectPagination(vo);
		PagedResult<DepartmentEO> page = PagedBeanUtil.toPagedResult(list);
		PagedResult<DepartmentVO> result = new PagedResult<>();
		BeanUtils.copyProperties(page, result);
		if (!XTListUtils.isEmpty(list)) {
			List<Long> ids = XTEntityUtils.getIdList(list);
			List<DepartmentVO> voList = new ArrayList<DepartmentVO>();
			Map<Long, FileEO> files = fileService.getMapTopOne(ids, DepartmentEO.class.getName(), null);
			for (DepartmentEO departmentEO : list) {
				DepartmentVO d = new DepartmentVO();
				BeanUtils.copyProperties(departmentEO, d);
				voList.add(d);
				FileEO file = files.get(d.getId());
				if (file != null) {
					d.getFiles().add(file.getId());
				}
			}
			result.setDataList(voList);
		}
		return result;
	}

	@Override
	public List<DepartmentVO> queryDepartmentForList() {
		List<DepartmentVO> list = Lists.newArrayList();

		// 查询部门信息
		List<DepartmentEO> departmentEOList = departmentMapper.selectAll();
		if (CollectionUtils.isEmpty(departmentEOList)) {
			return list;
		}

		// 赋值
		departmentEOList.stream().forEach(departmentEO -> {
			DepartmentVO departmentVO = new DepartmentVO();
			BeanUtils.copyProperties(departmentEO, departmentVO);
			list.add(departmentVO);
		});

		// 查询图片信息
		List<Long> caseIds = list.stream().map(departmentVO -> departmentVO.getId()).distinct()
				.collect(Collectors.toList());
		List<FileEO> fileEOList = fileService.getList(caseIds, DepartmentEO.class.getName(), null);
		if (CollectionUtils.isEmpty(fileEOList)) {
			return list;
		}

		for (DepartmentVO  vo : list){
			for (FileEO fileEO : fileEOList){
				if (vo.getId().equals(fileEO.getCaseId())) {
					vo.setFileAction(FileUrlAdapter.assemblyAction(fileEO.getId()));
					continue;
				}
			}
		}
		return list;
	}

	@Override
	public List<DepartmentVO> queryDepartmentAndUserForList(String userIds,String type) {
		List<DepartmentVO> list = Lists.newArrayList();

		// 查询部门信息
		List<DepartmentEO> departmentEOList = departmentMapper.selectAll();
		if (CollectionUtils.isEmpty(departmentEOList)) {
			return list;
		}
		int flag = 0;
		// 赋值
		for (DepartmentEO departmentEO : departmentEOList) {
			flag+=1;
			DepartmentVO departmentVO = new DepartmentVO();
			BeanUtils.copyProperties(departmentEO, departmentVO);
			if(flag==1) {
				departmentVO.setSpread(Boolean.TRUE);
			}
			List<Long> ids = null;
			if(!XTStringUtils.isEmpty(userIds)) {
				List<String>	users = Arrays.asList(userIds.split(","));
				ids=new ArrayList<>();
				for (String s : users) {
					ids.add(Long.valueOf(s));
				}
			}
			// 人员信息
			List<SysUserVO> sysUserVOList = deptUserService.queryDeptUserList(departmentVO.getId());
			if (!CollectionUtils.isEmpty(sysUserVOList)){
				List<SysUserVO> userList= new  ArrayList<>();
				for (SysUserVO user : sysUserVOList) {
					if(type.equals(user.getType())) {
						userList.add(user);
					}
				}
				if (!CollectionUtils.isEmpty(sysUserVOList)){
				for (SysUserVO user : userList) {
				if(!XTListUtils.isEmpty(ids)) {//是否被选中
					if(ids.contains(user.getId())) {
							user.setSelect(Boolean.TRUE);
							departmentVO.setSpread(Boolean.TRUE);
						}
					}	
				}
				}
				departmentVO.setSysUserVOList(userList);
			}
			list.add(departmentVO);
		}

		return list;
	}

	@Override
	public List<DepartmentEO> getDepartmentsByIdList(List<Long> deptIds) {

		List<DepartmentEO> departmentEOS = departmentMapper.selectByIdList(deptIds);

		return departmentEOS;
	}

	@Override
	public Map<Long, DepartmentEO> getMapToOneByIdList(List<Long> deptIds) {
		Map<Long,DepartmentEO> result = null;
		List<DepartmentEO> departmentEOS = departmentMapper.selectByIdList(deptIds);
		if(!CollectionUtils.isEmpty(departmentEOS)){
			result = new HashMap<Long,DepartmentEO>();
			for (DepartmentEO departmentEO : departmentEOS) {
				if (!result.containsKey(departmentEO.getId())) {// 第一次添加
					result.put(departmentEO.getId(), departmentEO);
				}
			}
		}

		return result;
	}

	@Override
	public DepartmentVO queryDepartmentInfo(Long id) {

		DepartmentVO departmentVO = new DepartmentVO();

		// 部门基本信息
		DepartmentEO departmentEO = departmentMapper.selectByPrimaryKey(id);
		if (departmentEO == null) {
			return departmentVO;
		}

		BeanUtils.copyProperties(departmentEO, departmentVO);

		// 部门内容
		ContentEO contentEO = contentService.queryContentByTypeAndId(BusinessEnum.TYPE_DEPARTMENT.getCode(),
				departmentVO.getId());
		if (contentEO != null) {
			departmentVO.setContent(contentEO.getContent());
		}

		// 图片信息
		List<Long> fileIds = fileService.getFileByCaseId(departmentVO.getId(), DepartmentEO.class.getName(), null);
		if (!CollectionUtils.isEmpty(fileIds)) {
			departmentVO.setFileAction(FileUrlAdapter.assemblyAction(fileIds.get(0)));
		}

		// 人员信息
		List<SysUserVO> sysUserVOList = deptUserService.queryDeptUserList(departmentVO.getId());
		if (!CollectionUtils.isEmpty(sysUserVOList)) {
			//用户图片
			List<Long> caseIds = sysUserVOList.stream().map(SysUserVO::getId).distinct().collect(Collectors.toList());
			List<FileEO> fileEOList = fileService.getFileByIds(caseIds,SysUser.class.getName(),null);
			if (!CollectionUtils.isEmpty(fileEOList)){
				for (SysUserVO vo : sysUserVOList){
					for (FileEO fileEO : fileEOList){
						if(vo.getId().equals(fileEO.getCaseId())){
							vo.setFileAction(FileUrlAdapter.assemblyAction(fileEO.getId()));
						}
					}
				}
			}
			departmentVO.setSysUserVOList(sysUserVOList);
		}
		return departmentVO;
	}

	@Override
	public void saveInfo(DepartmentVO vo) throws XTBusinessException {
		DepartmentEO eo = new DepartmentEO();
		BeanUtils.copyProperties(vo, eo);
		eo.setStatus(EStatus.active.getCode());
		this.save(eo);
		if (!XTListUtils.isEmpty(vo.getFiles())) {
			fileService.updateList(vo.getFiles(), eo.getId(), DepartmentEO.class.getName());
		}
		if (vo.getBasicFunction() != null) {
			contentService.saveOrUpdate(BusinessEnum.TYPE_DEPARTMENT.getCode(), eo.getId(), vo.getBasicFunction());
		}
	}

	@Override
	public void updateInfo(DepartmentVO vo) throws XTBusinessException {
		DepartmentEO eo = new DepartmentEO();
		BeanUtils.copyProperties(vo, eo);
		eo.setStatus(EStatus.active.getCode());
		this.updateByPrimaryKeySelective(eo);
		fileService.updateList(vo.getFiles(), eo.getId(), DepartmentEO.class.getName());
		// 更新内容
		contentService.saveOrUpdate(BusinessEnum.TYPE_DEPARTMENT.getCode(), eo.getId(), vo.getBasicFunction());
	}

	@Override
	public DepartmentEO getByPrimaryKey(Long id) throws XTBusinessException {
		DepartmentEO dept = super.getByPrimaryKey(id);
		if (dept != null) {
			dept.setBasicFunction(getContent(id));
		}
		return dept;
	}

	private String getContent(Long id) {
		ContentEO content = contentService.queryContentByTypeAndId(BusinessEnum.TYPE_DEPARTMENT.getCode(), id);
		if (content != null) {
			return content.getContent();
		}
		return null;
	}

	@Override
	public DepartmentVO getInfo(Long id) throws XTBusinessException {
		DepartmentEO dept = super.getByPrimaryKey(id);
		if (dept != null) {
			DepartmentVO vo = new DepartmentVO();
			BeanUtils.copyProperties(dept, vo);
			vo.setBasicFunction(getContent(id));
			List<FileEO> files = fileService.getFileById(id, DepartmentEO.class.getName(), null);
			if(!XTListUtils.isEmpty(files)) {
				vo.setFiles(XTEntityUtils.getIdList(files));
				vo.setFileAction(FileUrlAdapter.assemblyAction(files.get(0).getId()));
			}
			vo.setFileEOList(files);
			return vo;
		}

		return null;
	}
}
